﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using StockTrader.BusinessService.DataContract.Mortgate;
using LoanMonitor.Business;
using TCKQKL.FrontEnd.DataModel;
using Mortgage.DAL;
using Mortgage.Enum;

namespace LoanMonitor.Utils
{
    public partial class frmLiquidate : Form
    {
        private MortgageMornitorDAL client = new MortgageMornitorDAL();
        private DALclient history = new DALclient();
        private bool isContractReady = false;

        public frmLiquidate()
        {
            InitializeComponent();
        }

        private void btnSearchContract_Click(object sender, EventArgs e)
        {
            List<ContractData> contracts = client.searchContract(
                                            txtPContractNo.Text, txtIDCardNo.Text,
                                            dtFrom.Value, dtTo.Value, 0, 0,
                                            Convert.ToInt32(ContracType.Loan),
                                            ContractStatus.Open.ToString(),
                                            txtAccNo.Text, string.Empty);

            grvContractList.DataSource = contracts;

            if (contracts.Count > 0)
                FormatContractList(contracts);

        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            //Find in the local database
            AccountData customer = client.getCustomerByID(txtIDCardNo.Text);
            UpdateCustomerInfo(customer);

            //Find in BOSC database

            //Update fee information

            //Create new
            if (customer == null)
                MessageBox.Show("Chưa có thông tin về khách hàng này.", "Oops!");
        }

        private void UpdateCustomerInfo(AccountData customer)
        {
            if (customer != null)
            {
                txtAccName.Text = customer.Name;
                txtAccIdCardNo.Text = customer.IDcardNo;
                txtAccIdCardDate.Text = customer.IDcardDate.ToString("ddMMyyyy");
                txtAccIdCardIssuer.Text = customer.IDcardIssuer;
                txtAccNo.Text = customer.AccountNo;
                txtAccMobile.Text = customer.PhoneMobile;
                txtAccFix.Text = customer.PhoneFix;
                txtAccContact.Text = customer.AddressContact;
                txtAccResident.Text = customer.AddressResident;
                txtAccEmail.Text = customer.Email;
                rdAccIsMale.Checked = (customer.Gender.Equals("Nam")) ? true : false;

                List<string> accounts = client.getCustomerAccounts(customer.IDcardNo);
                lstAccountNo.Items.Clear();
                foreach (string acc in accounts)
                    lstAccountNo.Items.Add(acc);

            }
        }

        private void FormatContractList(List<ContractData> list)
        {
            grvContractList.Columns["ContractNo"].DisplayIndex = 0;
            grvContractList.Columns["StartDate"].DisplayIndex = 1;
            grvContractList.Columns["EndDate"].DisplayIndex = 2;
            grvContractList.Columns["Fee"].DisplayIndex = 3;
            grvContractList.Columns["Fee"].DefaultCellStyle.Format = "N3";
            grvContractList.Columns["PenaltyFee"].DisplayIndex = 4;
            grvContractList.Columns["PenaltyFee"].DefaultCellStyle.Format = "N3";
            grvContractList.Columns["ProcessFee"].DisplayIndex = 5;
            grvContractList.Columns["ProcessFee"].DefaultCellStyle.Format = "N0";
            grvContractList.Columns["ContractValue"].DisplayIndex = 6;
            grvContractList.Columns["ContractValue"].DefaultCellStyle.Format = "N0";

            grvContractList.Columns["ContractNo"].HeaderText = "Số hợp đồng";
            grvContractList.Columns["StartDate"].HeaderText = "Ngày bắt đầu";
            grvContractList.Columns["EndDate"].HeaderText = "Ngày hết hạn";
            grvContractList.Columns["Fee"].HeaderText = "Phí cơ bản";
            grvContractList.Columns["PenaltyFee"].HeaderText = "Phí phạt quá hạn";
            grvContractList.Columns["ProcessFee"].HeaderText = "Phí xét duyệt";
            grvContractList.Columns["ContractValue"].HeaderText = "Giá trị";

            grvContractList.Columns["ContractType"].Visible = false;
            grvContractList.Columns["CustomerID"].Visible = false;
        }

        private void btnLiquidate_Click(object sender, EventArgs e)
        {
            try
            {
                ContractData contract = client.getContractByNo(txtPContractNo.Text);
                string ContractNo = contract.ContractNo.Replace("P", "S");

                decimal liquidateAmount = getLiquidated(contract.ContractNo);
                if (chkLiquidateAll.Checked)
                {


                    List<ContractData> relateContracts = client.searchContract(string.Empty, string.Empty,
                                        DateTime.Now, DateTime.Now, 0, 0, -1,
                                        ContractStatus.Open.ToString(),
                                        string.Empty, contract.ContractNo);

                    foreach (ContractData ct in relateContracts)
                        client.InsertContract(ct.ContractNo, contract.CustomerID,
                                        contract.StartDate, contract.EndDate,
                                        contract.Fee, contract.PenaltyFee, contract.ProcessFee,
                                        Convert.ToInt32(ContracType.Loan),
                                        ContractStatus.Closed.ToString(),
                                        contract.ContractValue, txtAccNo.Text, contract.OriginalContract);

                    // Update original contract as close
                    client.InsertContract(contract.ContractNo, contract.CustomerID,
                                        contract.StartDate, contract.EndDate,
                                        contract.Fee, contract.PenaltyFee, contract.ProcessFee,
                                        Convert.ToInt32(ContracType.Loan),
                                        ContractStatus.Closed.ToString(),
                                        contract.ContractValue, txtAccNo.Text, contract.OriginalContract);

                    //Insert a liquidate contract
                    client.InsertContract(ContractNo, contract.CustomerID,
                                        contract.StartDate, contract.EndDate,
                                        contract.Fee, contract.PenaltyFee, contract.ProcessFee,
                                        Convert.ToInt32(ContracType.Liquidate),
                                        ContractStatus.Closed.ToString(),
                                        contract.ContractValue, txtAccNo.Text, contract.OriginalContract);

                    client.InsertMortgageTrans(txtAccNo.Text, txtSContractNo.Text,
                                                DateTime.Now, contract.ContractNo,
                                                Convert.ToInt32(TransType.DepositCash),
                                                0, contract.ContractValue - liquidateAmount);

                }
                else
                {
                    decimal cashIn = Convert.ToDecimal(txtMortgageAmount.Text);

                    client.InsertContract(ContractNo, contract.CustomerID,
                                            contract.StartDate, contract.EndDate,
                                            contract.Fee, contract.PenaltyFee, contract.ProcessFee,
                                            Convert.ToInt32(ContracType.Liquidate),
                                            ContractStatus.Open.ToString(),
                                            cashIn, txtAccNo.Text, contract.ContractNo);

                    client.InsertMortgageTrans(txtAccNo.Text, txtSContractNo.Text,
                                                DateTime.Now, contract.ContractNo,
                                                Convert.ToInt32(TransType.DepositCash), 0, cashIn);
                    txtMortgageAmount.Text = "0";
                    txtAccLiquidated.Text = getLiquidated(txtPContractNo.Text).ToString("N0");
                }
                MessageBox.Show("Hợp đồng số " + ContractNo + " đã tạo thành công!");
                //ResetSearchConditions();
                btnSearchContract_Click(sender, e);


            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message + ". Hợp đồng chưa được tạo!");
            }

        }

        private void ResetSearchConditions()
        {
            txtPContractNo.Text = string.Empty;
            dtFrom.Value = DateTime.Now;
            dtTo.Value = DateTime.Now;
            txtAccNo.Text = string.Empty;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chkLiquidateAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chkLiquidateAll.Checked)
                {
                    ContractData contract = client.getContractByNo(txtPContractNo.Text);
                    decimal liquidateAmount = getLiquidated(contract.ContractNo);
                    txtMortgageAmount.Text = (contract.ContractValue - liquidateAmount).ToString("N0");
                    txtMortgageAmount.ReadOnly = true;
                }
                else
                    txtMortgageAmount.ReadOnly = false;
            }
            catch
            {
                return;
            }
        }

        private void txtIDCardNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                btnFindCustomer();
        }

        private void btnFindCustomer()
        {
            //Find in the local database
            AccountData customer = client.getCustomerByID(txtIDCardNo.Text);
            UpdateCustomerInfo(customer);

            //Find in BOSC database

            //Update fee information

            //Create new
            if (customer == null)
                MessageBox.Show("Chưa có thông tin về khách hàng này.", "Oops!");
        }

        private void lstAccountNo_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (lstAccountNo.SelectedItem != null)
            {
                txtAccNo.Text = lstAccountNo.SelectedItem.ToString();
                AccountData customer = history.getCustomerInfo(txtAccNo.Text);

                txtAccName.Text = customer.Name;
                txtAccIdCardNo.Text = customer.IDcardNo;
                txtAccIdCardDate.Text = customer.IDcardDate.ToString("dd/MM/yyyy");
                txtAccIdCardIssuer.Text = customer.IDcardIssuer;
                txtAccNo.Text = customer.AccountNo;
                txtAccMobile.Text = customer.PhoneMobile;
                txtAccFix.Text = customer.PhoneFix;
                txtAccContact.Text = customer.AddressContact;
                txtAccResident.Text = customer.AddressResident;
                txtAccEmail.Text = customer.Email;
                rdAccIsMale.Checked = (customer.Gender.Equals("Nam")) ? true : false;
            }

            ResetContractInfo();

        }

        private void ResetContractInfo()
        {
            txtAccLiquidated.Text = "0";
            txtFeeAmount.TextBox1.Text = "0";
            txtSContractNo.Text = string.Empty;
            txtMortgageAmount.Text = "0";
        }

        private void txtAccNo_TextChanged(object sender, EventArgs e)
        {
            btnSearchContract_Click(sender, e);
        }

        private void txtAccNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                btnSearchContract_Click(sender, e);
        }

        private void grvContractList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            txtMortgageAmount.Text = "0";

            if (grvContractList.SelectedRows.Count > 0)
            {
                DataGridViewRow row = grvContractList.SelectedRows[0];
                if (!string.IsNullOrEmpty(row.Cells["ContractNo"].Value.ToString()))
                {

                    ContractData ctr = client.getContractByNo(row.Cells["ContractNo"].Value.ToString());
                    txtPContractNo.Text = ctr.ContractNo;
                    txtSContractNo.Text = ctr.ContractNo.Replace("P", "S");
                    txtContractValue.Text = ctr.ContractValue.ToString("N0");
                }

                //Update liquidated amount

                txtAccLiquidated.Text = getLiquidated(txtPContractNo.Text).ToString("N0");

                //Calculate and update fee
            }

        }

        private decimal getLiquidated(string OrignalContractNo)
        {
            decimal liquidatedAmount = 0;
            List<ContractData> Liquidateds = client.searchContract(string.Empty, string.Empty,
                                                DateTime.Now, DateTime.Now, 0, 0,
                                                Convert.ToInt32(ContracType.Liquidate),
                                                ContractStatus.Open.ToString(),
                                                txtAccNo.Text, txtPContractNo.Text);

            foreach (ContractData liq in Liquidateds)
            {
                List<MortgageTrans> trans = client.searchMortgageTrans(string.Empty,
                                                string.Empty, liq.ContractNo, DateTime.Now,
                                                DateTime.Now, Convert.ToInt32(TransType.DepositCash),
                                                0, 0, 0, 0);
                foreach (MortgageTrans tran in trans)
                    liquidatedAmount += tran.Debit;
            }
            return liquidatedAmount;
        }

        private void txtSContractNo_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSContractNo.Text))
                btnLiquidate.Enabled = false;
            else
                btnLiquidate.Enabled = true;
        }

        private void frmLiquidate_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSContractNo.Text))
                btnLiquidate.Enabled = false;
            else
                btnLiquidate.Enabled = true;
        }

        private void txtMortgageAmount_TextChanged(object sender, EventArgs e)
        {
            string s = ((TextBox)sender).Text.Trim();
            char[] ch = s.ToCharArray();

            StringBuilder sb = new StringBuilder();

            foreach (char c in ch)
            {
                if (Char.IsDigit(c))
                {
                    sb.Append(c);
                }
            }

            if (sb.Length >= 1)
            {
                ((TextBox)sender).Text = Convert.ToDecimal(sb.ToString()).ToString("N0");
                ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
            }
            else
            {
                ((TextBox)sender).Clear();
            }
            if (string.IsNullOrEmpty(txtMortgageAmount.Text) || Convert.ToDecimal(txtMortgageAmount.Text).Equals(0))
                txtSContractNo.Text = string.Empty;


            txtAccRemain.Text = string.IsNullOrEmpty(txtContractValue.Text) ?
                                string.Empty : (Convert.ToDecimal(txtContractValue.Text) -
                                Convert.ToDecimal(txtAccLiquidated.Text) -
                                Convert.ToDecimal(txtMortgageAmount.Text)).ToString("N0");
        }
    }
}
